<template>
  <div class="dataBase">
    <ContentWrap>
      <el-form
        label-width="140px"
        ref="formRef"
        :model="searchValue"
        v-if="infoShowList && infoShowList.length"
      >
        <el-row>
          <el-col :span="6" v-if="infoShowList[5].query">
            <el-form-item label="数据标准" prop="template">
              <el-select
                v-model="searchValue.template"
                clearable
                placeholder="请选择数据标准"
                filterable
                @change="templateChange"
              >
                <el-option
                  v-for="(template, templateIndex) in templateList"
                  :key="templateIndex"
                  :label="template.dataStandardName"
                  :value="template.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[0].query">
            <el-form-item label="id" prop="id">
              <ns-input v-model="searchValue.id" clearable placeholder="请输入id" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[1].query">
            <el-form-item label="文件名称" prop="fileName">
              <ns-input v-model="searchValue.fileName" clearable placeholder="请输入文件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[2]?.query">
            <el-form-item label="文件大小" prop="fileSize">
              <ns-input v-model="searchValue.fileSize" clearable placeholder="请输入文件大小" />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[3]?.query">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-form-item label="文件指纹" prop="figureType">
                  <el-select placeholder="请选择指纹类型" v-model="searchValue.figureType">
                    <el-option
                      v-for="item in figureTypes"
                      :label="item.name"
                      :value="item.name"
                      :key="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="" prop="figureValue" label-width="0">
                  <ns-input
                    v-model="searchValue.figureValue"
                    clearable
                    placeholder="请输入指纹内容"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="6" v-if="infoShowList[4]?.query">
            <el-form-item label="文件来源" prop="source">
              <el-select v-model="searchValue.source" clearable placeholder="请选择文件来源">
                <el-option label="手动上传" :value="3" />
                <el-option label="转储文件" :value="4" />
                <el-option label="监测平台" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="infoShowList[6].query">
            <el-form-item label="归属机构" prop="deptId">
              <el-cascader
                v-model="searchValue.deptId"
                clearable
                placeholder="请选择归属机构"
                :options="options"
                :props="cascaderProps"
                filterable
                :filter-method="sysFilterMethod"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[7].query">
            <el-form-item label="归属系统" prop="sysId">
              <el-cascader
                v-model="searchValue.sysId"
                placeholder="请选择归属系统"
                :props="systemCascaderProps"
                :options="systemList"
                filterable
                :filter-method="sysFilterMethod"
                clearable
            /></el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[8]?.query">
            <el-form-item label="分类" prop="classification">
              <el-cascader
                v-model="searchValue.classification"
                placeholder="请选择分类"
                :props="classificationCascaderProps"
                :options="classificationList"
                filterable
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[9].query">
            <el-form-item label="分级" prop="level">
              <el-select v-model="searchValue.level" clearable placeholder="请选择分级">
                <el-option
                  v-for="(level, levelIndex) in levelList"
                  :key="levelIndex"
                  :label="level.levelName"
                  :value="level.levelCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[10]?.query">
            <el-form-item label="保密期限" prop="institutionFiled3">
              <ns-input
                v-model="searchValue.institutionFiled3"
                clearable
                placeholder="请选择保密期限"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[11]?.query">
            <el-form-item label="定密日期" prop="filed1Range">
              <el-date-picker
                style="width: 90%"
                v-model="searchValue.filed1Range"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="YYYY/MM/DD"
                time-format="hh:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[12]?.query">
            <el-form-item label="解密日期" prop="filed2Range">
              <el-date-picker
                style="width: 90%"
                v-model="searchValue.filed2Range"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                date-format="YYYY/MM/DD"
                time-format="hh:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[13]?.query">
            <el-form-item label="到期后变更等级" prop="deadlineLevel">
              <el-select
                v-model="searchValue.deadlineLevel"
                clearable
                placeholder="请选择到期后变更等级"
              >
                <el-option
                  v-for="(level, levelIndex) in levelList"
                  :key="levelIndex"
                  :label="level.levelName"
                  :value="level.levelCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[14]?.query">
            <el-form-item label="分级进度" prop="process">
              <el-input
                :min="0"
                :max="100"
                v-model="searchValue.process"
                clearable
                placeholder="请输入分级进度"
                @input="handleInput"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[15].query">
            <el-form-item label="自动分级状态" prop="autoClassStatus">
              <el-select
                v-model="searchValue.autoClassStatus"
                clearable
                placeholder="请选择分级状态"
              >
                <el-option
                  v-for="(item, index) in autoClassStatusMap"
                  :key="index"
                  :label="item[1]"
                  :value="item[0]"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[16]?.query">
            <el-form-item label="自动分级时间" prop="autoClassificationTime">
              <el-date-picker
                v-model="searchValue.autoClassificationTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="infoShowList[17]?.query">
            <el-form-item label="提交状态" prop="submitStatus">
              <el-select v-model="searchValue.submitStatus" clearable placeholder="请选择提交状态">
                <el-option label="未提交" value="0" />
                <el-option label="已提交" value="1" />
                <!-- <el-option label="已取消" :value="4" /> -->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否已分级">
              <el-select v-model="searchValue.isLevel" clearable placeholder="请选择是否已分级">
                <el-option label="已分级" :value="true" />
                <el-option label="未分级" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否查询关联标准" prop="isSearchSon">
              <el-select
                v-model="searchValue.isSearchSon"
                clearable
                placeholder="请选择是否查询关联标准"
              >
                <el-option label="是" :value="true" />
                <el-option label="否" :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="route.name == 'ExitFile'">
            <el-form-item label="批次号码" prop="batchNum">
              <ns-input type="number" v-model="searchValue.batchNum" placeholder="请输入批次号码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="searchValue.auditStatus" clearable placeholder="请选择审核状态">
                <el-option label="审核中" :value="1" />
                <el-option label="审核通过" :value="2" />
                <el-option label="审核拒绝" :value="3" />
                <el-option label="待处理" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="text-right">
            <el-button @click="search" type="primary">搜索</el-button>
            <el-button @click="searchReset" plain>重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-form-item>
        <el-button type="primary" @click="uploadFile" v-hasPermi="['assetList:fileList:add']">
          新增</el-button
        >
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="submitEnsureList"
          v-hasPermi="['assetList:fileList:confirm']"
        >
          提交确认</el-button
        >
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="openAutoClassification"
          v-hasPermi="['assetList:fileList:autoClass']"
          >智能分类分级</el-button
        >
        <el-button
          type="primary"
          :disabled="ids.length == 0"
          @click="handleUpdateList"
          v-hasPermi="['assetList:fileList:listClass']"
          >批量修改</el-button
        >
        <el-button @click="handleExport" v-hasPermi="['assetList:fileList:export']">
          导出</el-button
        >
        <el-button @click="handleImport" v-hasPermi="['assetList:fileList:import']">
          导入</el-button
        >

        <el-button
          :disabled="ids.length == 0"
          type="danger"
          @click="delList"
          v-hasPermi="['assetList:fileList:delete']"
        >
          删除
        </el-button>
        <el-button @click="handleEditInfo" v-hasPermi="['assetList:fileList:showInfo']"
          >信息展示设置</el-button
        >
      </el-form-item>
      <AsyncTable
        v-bind="tableInfo"
        ref="tableRef"
        :fetchData="fetchData"
        @selection-change="changeTable"
      />
    </ContentWrap>
    <ImportForm ref="importFormRef" @success="search" />
    <!-- 批量修改分类分级弹窗 -->
    <UpdateListLevel ref="updateListRef" @success="search" type="outside" />
    <InfoShow ref="dialogRef" @success="getInfoShowConf" />
  </div>
</template>

<script setup lang="tsx">
import { sysFilterMethod } from '@/utils/selectFilter'
import UpdateListLevel from '@/views/asset/assetList/databaseList/detail/components/updateListLevel.vue'
import ImportForm from '@/views/asset/assetList/components/ImportForm.vue'
import { ElMessage } from 'element-plus'
import AsyncTable from '@/components/AsyncTable'
import { useRouter } from 'vue-router'
import * as api from '@/api/dataSourceManage/index'
import InfoShow from '@/views/assetManage/components/infoShow.vue'
import * as infoShowApi from '@/api/infoShow/index'
import {
  getDataBaseList,
  assetDel,
  assetListDel,
  assetEnsure,
  assetListEnsure,
  assetMessageExportExcelFile
} from '@/api/assetList/index'
import { getFingerType } from '@/api/develop/featureLibrary/fingerprint'
import { getSimpleDeptList } from '@/api/system/dept'
import { getSimpleSystemList } from '@/api/asset/taskManage'
import { levelPage } from '@/api/strategyManage/level/index'
import { dataClassificationTree } from '@/api/dataStandards/classification/index'
import { handleTree } from '@/utils/tree'
import { autoClassStatusMap } from '@/utils/dict'
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
import {
  renderFinger,
  sourceRender,
  renderClassification,
  renderLevel,
  autoClassStatusRender
} from '@/utils/commonRender'
import { checkPermi } from '@/utils/permission'
import download from '@/utils/download'
import { dataStandardsPage } from '@/api/dataStandards/standards/index'
const systemList = ref([
  {
    id: 1,
    name: '系统1',
    children: [
      { id: 11, name: '子系统1' },
      { id: 12, name: '子系统2' },
      { id: 13, name: '子系统3' }
    ]
  }
])
const tableRef = ref()
const formRef = ref()
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const router = useRouter()
const route = useRoute()
console.log('route', route)
const message = useMessage() // 消息弹窗
const ids = ref<string[]>([])
const cascaderProps = ref({
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false
})
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'text',
  value: 'id',
  children: 'children',
  emitPath: false
})
const systemCascaderProps = {
  checkStrictly: true,
  label: 'value',
  value: 'id',
  children: 'children',
  emitPath: false
}
function traverseTree(data) {
  const updatedTree = []
  for (let i = 0; i < data.length; i++) {
    const node = data[i] // 创建新节点并添加 disable 属性
    if (node.pid == '-1') {
      node.disabled = true
    }
    updatedTree.push(node)
    if (node.children && node.children.length > 0) {
      node.children = traverseTree(node.children) // 递归遍历子节点并更新子树结构
    }
  }
  return updatedTree
}
// 所有指纹类型
const figureTypes = ref([])
/** 获取指纹类型 */
const getTypes = async () => {
  const res = await getFingerType()
  figureTypes.value = Object.entries(res).map(([key, value]) => {
    return {
      name: value as string,
      value: key
    }
  })
}

const classificationList = ref([])
const classificationListCopy = ref([])
const getClassificationList = async () => {
  const data = await dataClassificationTree({ type: 0 })
  classificationList.value = traverseTree(data)
  classificationListCopy.value = traverseTree(data)
}
const options = ref<Tree[]>([])
const assetTypeList = ref([])

/**
 * @description: 选取列表时获取列表id
 * @param {*} val
 */
const changeTable = (val) => {
  ids.value = []
  val.map((item) => {
    ids.value.push(item.id)
  })
}
const searchReset = () => {
  formRef.value.resetFields()
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}
const searchValue = ref({
  fileName: '',
  fileType: '',
  level: '',
  importance: '',
  sysId: '',
  deptId: '',
  isLevel: '',
  submitStatus: '',
  isSearchSon: '',
  template: '',
  batchNum: route.name == 'ExitFile' ? '*' : null,
  auditStatus: '',
  id: '',
  process: undefined,
  institutionFiled3: '',
  filed2Range: '',
  filed1Range: '',
  deadlineLevel: '',
  autoClassStatus: ''
})

const allSelect = ref(false)

const search = () => {
  tableRef.value.resetPage()
  tableRef.value.fetchData()
}

// 使用正则表达式只允许输入0-9的数字
function handleInput(value) {
  const filteredValue = value.replace(/[^0-9]/g, '')

  if (filteredValue !== searchValue.value.process) {
    searchValue.value.process = filteredValue
  }
}

//根据数据标准筛选分类
const templateChange = () => {
  if (searchValue.value.template) {
    classificationList.value = classificationListCopy.value.filter(
      (item) => item.id == searchValue.value.template
    )
    searchValue.value.classification = ''
  } else {
    classificationList.value = classificationListCopy.value
  }
}

const tableInfo = reactive({
  columns: [
    {
      type: 'selection'
    },
    { label: 'id', prop: 'id' },
    { label: '文件名称', width: '100px', prop: 'fileName' },
    { label: '文件类型', width: '100px', prop: 'fileType' },
    { label: '文件大小', width: '100px', prop: 'fileSize' },
    { label: '文件指纹', width: '150px', render: renderFinger },
    { label: '文件来源', width: '100px', render: sourceRender },
    {
      label: '数据标准',
      width: '100px',
      prop: 'templateName'
    },
    {
      label: '归属机构',
      width: '100px',
      prop: 'deptName'
    },
    {
      label: '归属系统',
      width: '100px',
      prop: 'sysName'
    },
    {
      label: '分类',
      render: renderClassification
    },
    {
      label: '分级',
      render: renderLevel
    },
    {
      label: '保密期限',
      width: '200px',
      prop: 'institutionFiled3'
    },
    {
      label: '定密日期',
      width: '200px',
      prop: 'field1'
    },
    {
      label: '解密日期',
      width: '200px',
      prop: 'field2'
    },
    {
      label: '到期后变更等级',
      width: '200px',
      prop: 'deadlineLevelName'
    },
    // {
    //   label: '重要程度',
    //   render: ({ row }) => {
    //     return (
    //       <>
    //         <span>{row.handImportance || row.importance || '--'}</span>
    //       </>
    //     )
    //   }
    // },
    {
      label: '分级进度',
      width: '100px',
      render: ({ row }) => {
        return (
          <>
            <span>{row.process}%</span>
          </>
        )
      }
    },
    {
      label: '自动分级状态',
      width: '120px',
      render: autoClassStatusRender
    },
    {
      label: '自动分级时间',
      width: '200px',
      prop: 'autoClassificationTime'
    },
    {
      label: '提交状态',
      width: '100px',
      render: ({ row }) => {
        return <>{row.submitStatus == '1' ? '已提交' : '未提交'}</>
      }
    },
    {
      label: '操作项',
      width: '250px',
      fixed: 'right',
      render: ({ row }) => {
        return (
          <>
            {row.submitStatus != '1' && checkPermi(['assetList:fileList:FileListConfirm']) ? (
              <el-button
                link
                type="primary"
                onClick={() => {
                  submitEnsure(row)
                }}
              >
                提交确认
              </el-button>
            ) : (
              <div></div>
            )}
            {checkPermi(['assetList:fileList:edit']) && (
              <el-button
                link
                type="primary"
                onClick={() => {
                  gotoDetail(row)
                }}
              >
                编辑
              </el-button>
            )}
            {checkPermi(['assetList:fileList:singleDelete']) && (
              <ns-button
                style="margin-left:6px"
                link
                type="danger"
                confirm
                onClick={() => {
                  del(row)
                }}
              >
                删除
              </ns-button>
            )}
          </>
        )
      }
    }
  ],
  data: []
})

const allSelectHandle = () => {
  allSelect.value = !allSelect.value
  tableRef.value.ignorePageSelect(allSelect.value)
}

const dialogRef = ref()
const handleEditInfo = () => {
  dialogRef.value.open('12')
}

// 获取信息展示
const infoShowList = ref()
const getInfoShowConf = async () => {
  const data = await infoShowApi.infoShowList({
    type: '12',
    language: location.href.indexOf('/en/') >= 0 ? 'en' : ''
  })
  infoShowList.value = data
  data.forEach((item, index) => {
    tableInfo.columns[index + 1].hide = item.show === 0 ? true : false
  })
}

const del = (row) => {
  assetDel(row.id).then((response) => {
    console.log('response', response)
    tableRef.value.fetchData()
    ElMessage.success('删除成功')
  })
}
const delList = () => {
  proxy?.$modal
    .confirm(`确定要删除所选数据吗？`)
    .then(() => {
      assetListDel(ids.value).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('删除成功')
      })
    })
    .catch(() => {})
}

const pageParams = ref({
  page: 1,
  pageSize: 10
})
console.log('route.name', route.name)
const fetchData = async ({ page, pageSize }) => {
  pageParams.value = {
    page,
    pageSize
  }
  const { data, count } = await getDataBaseList({
    page,
    pageSize,
    dataType: 'file',
    isSingle: true,
    batchNum: route.name == 'ExitFile' ? '*' : null,
    ...searchValue.value
  })
  return { data, count }
}
const gotoDetail = (row) => {
  proxy?.$Drawer({
    params: {
      ...row,
      type: row.handClassificationName ? `人工` : row.classificationName ? `自动` : '--',
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `分级分类`,
    size: '40%',
    component: import('@/views/asset/assetList/databaseList/detail/components/grade.vue')
  })
}

const openAutoClassification = () => {
  console.log('ids.value', ids.value)
  proxy?.$Drawer({
    params: {
      ids: ids.value,
      callBack: () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    },
    title: `添加分级对象`,
    size: '50%',
    component: import('@/views/asset/assetList/components/autoClassification.vue')
  })
}

const submitEnsure = (row) => {
  proxy?.$modal
    .confirm(`确定要将该资产提交至待确认吗？`)
    .then(() => {
      assetEnsure({
        id: row.id
      }).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('提交成功')
      })
    })
    .catch(() => {})
}
const submitEnsureList = () => {
  proxy?.$modal
    .confirm(`确定要将所选资产提交至待确认吗？`)
    .then(() => {
      assetListEnsure(ids.value).then((response) => {
        console.log('response', response)
        tableRef.value.fetchData()
        ElMessage.success('提交成功')
      })
    })
    .catch(() => {})
}

const exportLoading = ref(true)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await assetMessageExportExcelFile({
      ...pageParams.value,
      ...searchValue.value,
      dataType: 'file',
      isSingle: true,
      ids: ids.value
    })
    download.excel(data, '文件列表.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

//上传文件
const uploadFile = () => {
  proxy?.$Drawer({
    title: '新增',
    component: import('./uploadFile.vue'),
    size: '70%',
    params: {
      callBack: async () => {
        tableRef.value.resetPage()
        tableRef.value.fetchData()
      }
    }
  })
}

const getSystemList = async () => {
  const data = await getSimpleSystemList({})
  systemList.value = handleTree(data, 'id', 'pid')
}
const getDeptList = async () => {
  const data = await getSimpleDeptList()
  options.value = data
}
const getAssetType = async () => {
  const data = await api.getAssetTypeList({ datasourceType: 1 })
  assetTypeList.value = data
}
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}

// 批量修改
const updateListRef = ref()
const handleUpdateList = () => {
  updateListRef.value.open(ids.value, 'showConfirm')
}

// 数据标准
const templateList = ref([])
const getTemplateList = async () => {
  const { data } = await dataStandardsPage({ page: 1, pageSize: 999, status: '1', type: 0 })
  console.log('data', data)
  templateList.value = data
}

onMounted(() => {
  getInfoShowConf()
  getSystemList()
  getDeptList()
  getAssetType()
  getLevelList()
  getTemplateList()
  getClassificationList()
  getTypes()
})
</script>

<style lang="scss">
.dataBase {
  .el-dropdown-link {
    cursor: pointer;
    color: var(--el-color-primary);
    display: inline-flex;
    align-items: center;
    line-height: 23px;
    padding-left: 12px;
  }

  .el-form .el-select {
    width: 100%;
  }

  :deep(.hide-expand .cell) {
    display: none;
  }

  :deep(.el-form .el-cascader) {
    width: 100%;
  }

  :deep(.operate-btn .el-button.is-text) {
    padding: 0 10px 0 0;
  }

  .el-dropdown-link:focus {
    outline: none;
  }
}
</style>
